import json
import uuid
from random import Random

import requests
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import time
from tornado import gen
from tornado.concurrent import run_on_executor, Future
from concurrent.futures import ThreadPoolExecutor
from tornado.options import define, options

define("port", default=6001, help="run on the given port", type=int)
target = "http:127.0.0.1:5000"


class BaseHandler(tornado.web.RequestHandler):
    def send(self, obj):
        self.write(obj)


class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        greeting = self.get_argument('greeting', 'Hello')
        self.write(greeting + ', friendly user!')


def getContainerNum():
    strval = list("ABCDEFIGKLMNOPQRSTUVWXYZ0123456789" * 3)
    Random().shuffle(strval)
    return "".join(strval[:6])


class FristInspection(BaseHandler):
    def post(self, args=None):
        params = self.request.body
        params = json.loads(params)
        self.send({"msg": "接收成功", "success": True})
        data = {
            "recordId": params.get("recordId", 1),
            "lprNum": params.get("lprNum", "京Asa110"),
            "lprPicture": params.get("lprPicture", "http://127.0.0.1:9050/pic/110.jpg"),
            "ContainerNum": getContainerNum(),
        }
        r = requests.post(f"{target}/api/BindingResult", data)
        pass


class ManualCheck(BaseHandler):
    def post(self, args=None):
        params = self.get_argument("params", None)
        self.send({"msg": "接收成功", "success": True})


class CustomsLogin(BaseHandler):
    def post(self, args=None):
        params = self.request.body
        params = json.loads(params)
        self.send({"msg": "接收成功", "success": True})


'''
#辅助平台获取探测数据返回报关单编号
'''


class Declaration(BaseHandler):
    def post(self, args=None):
        params = self.request.body
        params = json.loads(params)
        print(params)
        dataId = params.get("PostDataId", 1)
        declaration = uuid.uuid1().__str__()
        self.send({"PostDataId": dataId, "Declaration": declaration})
        pass


class TestHandler(BaseHandler):
    """
    多线程 异步非阻塞
    """
    max_thread_num = 10
    executor = ThreadPoolExecutor(max_workers=max_thread_num)

    @run_on_executor
    def my_func(self, *args, **kwargs):
        p = args[0]
        time.sleep(10)
        return p

        # params = self.request.body
        # params = json.loads(params)
        # print(params)
        # # time.sleep(30)
        # self.send({"msg": "接收成功", "success": True})
        # self.finish()

    @gen.coroutine
    def post(self, args=None):
        params = self.request.body
        params = json.loads(params)
        res = yield self.my_func(params)
        self.send({"msg": "接收成功", "success": True, 'res': res})
        self.finish()


class Test2Handler(BaseHandler):
    """单线程 异步非阻塞"""
    def dosomework(self, p):
        time.sleep(10)
        print(p)
        self.send(p)
        self.finish()

    @gen.coroutine
    def post(self):
        params = self.request.body
        params = json.loads(params)
        f = Future()
        f.add_done_callback(self.dosomework(params))
        yield f


class Test3Handler(BaseHandler):
    """同步阻塞"""
    def post(self):
        params = self.request.body
        params = json.loads(params)
        print(params)
        time.sleep(10)
        self.send(params)


def getPoints():
    handlers = []
    handlers.extend({
        (r"/", IndexHandler),
        (r"/index.html", IndexHandler),
        (r'/api/FirstInspectData', FristInspection),
        (r'/api/ManualCheckResult', ManualCheck),
        (r'/api/CustomsLogin', CustomsLogin),
        (r'/api/Radiation/ReceiveRadiationInfo', FristInspection),
        (r'/api/Declaration', Declaration),  # 辅助平台获取探测数据返回报关单编号
        (r'/api/test', TestHandler),
        (r'/api/test2', Test2Handler),
        (r'/api/test3', Test3Handler),
    })
    return handlers


if __name__ == "__main__":
    tornado.options.parse_command_line()
    points = getPoints()
    app = tornado.web.Application(handlers=points)
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.bind(options.port)
    http_server.start()
    tornado.ioloop.IOLoop.instance().start()
